package data.join.com.utils;

import android.content.Context;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.text.TextUtils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import data.join.com.R;

/**
 * log日志统计保存
 * 
 * @author way
 * 
 */

public class LogcatHelper {
	public static final String TAG = "LogcatHelper";

	private static LogcatHelper INSTANCE = null;

	public static final String PATH_LOGCAT = "/sdcard/joinLog";

	private LogDumper mLogDumper = null;
	private int mPId;

	/**
	 * 
	 * 初始化目录
	 * 
	 * */
	public void init(Context context) {

		File file = new File(PATH_LOGCAT);
		if (!file.exists()) {
			file.mkdirs();
		}
	}

	public static LogcatHelper getInstance(Context context) {
		if (INSTANCE == null) {
			INSTANCE = new LogcatHelper(context);
		}
		return INSTANCE;
	}

	public String getLogFilePath(){
		if(mLogDumper!=null)
			return mLogDumper.getLogFilePath();
		else
			return null;
	}
	
	private LogcatHelper(Context context) {
		init(context);
		mPId = android.os.Process.myPid();
	}

	public void start() {
		if (mLogDumper == null){
			mLogDumper = new LogDumper(String.valueOf(mPId), PATH_LOGCAT);
			mLogDumper.start();
		}
	}

	public void stop() {
		if (mLogDumper != null) {
			mLogDumper.stopLogs();
			mLogDumper = null;
		}
	}

	private class LogDumper extends Thread {

		private Process logcatProc;
		private BufferedReader mReader = null;
		private boolean mRunning = true;
		String cmds = null;
		private String mPID;
		private FileOutputStream out = null;
		private String mLogFilePath;

		public LogDumper(String pid, String dir) {
			mPID = pid;
			try {
				mLogFilePath = dir + File.separator  + generateLogFile(dir);
				out = new FileOutputStream(new File(mLogFilePath));
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			/**
			 * 
			 * 日志等级：*:v , *:d , *:w , *:e , *:f , *:s
			 * 
			 * 显示当前mPID程序的 E和W等级的日志.
			 * 
			 * */

			// cmds = "logcat *:e *:w | grep \"(" + mPID + ")\"";
			//cmds = "logcat -v time | grep \"(" + mPID + ")\"";//打印所有日志信息
			cmds = "logcat -v time";//打印所有日志信息
			// cmds = "logcat -s way";//打印标签过滤信息
			//cmds = "logcat *:e *:i | grep \"(" + mPID + ")\"";

		}

		public void stopLogs() {
			mRunning = false;
		}
		
		public String getLogFilePath(){
			return mLogFilePath;
		}

		private String  generateLogFile(String dir){
			String logFile = "empty";
			try {
				if(TextUtils.isEmpty(dir)){

				}else{
					int lastCount;
					File file = new File(dir);
					File[] logs = file.listFiles(new FileFilter() {
						@Override
						public boolean accept(File pathname) {
							boolean ret = false;

							if(pathname.isFile() && pathname.isHidden() == false){
								if(isLogFile(pathname.getName())){
									ret = true;
								}
							}
							return ret;
						}
					});

					if(logs != null && logs.length>0){
						List<File> list = new ArrayList<>();

						for(File log:logs){
							list.add(log);
						}

						Collections.sort(list, new Comparator<File>() {
							@Override
							public int compare(File o1, File o2) {
								int ret = 0;
								int cmp1 = Integer.parseInt(o1.getName());
								int cmp2 = Integer.parseInt(o2.getName());

								if(cmp1 > cmp2){
									ret = 1;
								}else if(cmp1 < cmp2){
									ret = -1;
								}

								return ret;
							}
						});

						MyLog.D(TAG,"generateLogFile list.size()="+list.size());

						MyLog.D(TAG,"generateLogFile list.get(0)="+list.get(0));

						while (list.size() > 3){
							FileUtils.deleteFile(list.remove(0).getAbsolutePath());
						}

						lastCount = Integer.parseInt(list.get(list.size() - 1).getName()) + 1;

					}else{
						lastCount = 0;
					}

					logFile = String.format("%03d",lastCount);
				}
			}catch (Exception e){
				e.printStackTrace();
			}
			return logFile;
		}

		@Override
		public void run() {
			try {
				logcatProc = Runtime.getRuntime().exec(cmds);
				mReader = new BufferedReader(new InputStreamReader(logcatProc.getInputStream()), 1024);
				String line = null;
				while (mRunning && (line = mReader.readLine()) != null) {
					if (line.length() == 0) continue;

					if (out != null && line.contains(mPID)) {
						out.write((line + "\n").getBytes());
					}
				}
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (logcatProc != null) {
					logcatProc.destroy();
					logcatProc = null;
				}
				try {
					if (mReader != null) {
						mReader.close();
						mReader = null;
					}
					if (out != null) {
						out.close();
						out = null;
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	public static boolean isLogFile(String strEmail) {
		String strPattern = "[0-9]{3,}";
		Pattern p = Pattern.compile(strPattern);
		Matcher m = p.matcher(strEmail);
		return m.matches();
	}
}
